package com.chenfan.ccp.plug.business.send;

import com.chenfan.ccp.plug.business.entity.BusinessLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author xutong
 */
@Primary
@Slf4j
public class CompositeLogSender extends AbstractLogSender implements Ordered {
    private List<AbstractLogSender> senders;

    public CompositeLogSender(List<AbstractLogSender> senders) {
        this.senders = senders;
    }

    @Override
    public boolean send(BusinessLog businessLog) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        if (CollectionUtils.isEmpty(senders)) {
            return false;
        }
        senders.sort(new OrderComparator());
        for (AbstractLogSender sender : senders) {
            log.warn("#{}开始记录日志businessLog====={}", sender.getClass(), businessLog);
            if (sender.send(businessLog)) {
                return true;
            }
            log.warn("#{}记录日志失败切换到下一个sender记录日志,businessLog===={}", sender.getClass(), businessLog);
        }
        return false;
    }


    @Override
    public int getOrder() {
        return -1;
    }
}
